﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using MSH.Common.Helpers;
using MSH.Common.WP7;
using NHibernate;
using NHibernate.Linq;
using MSH.Common.Business;

namespace MSH.TaskServer.Tasks
{
    /// <summary>
    /// Taak die verantwoordelijk is voor het sturen van periodieke WP7 notificaties
    /// </summary>
    public class WP7NotificationTask
    {
        private System.Timers.Timer timer;
        private Double askForLocationToastTimespan = 0;

        public WP7NotificationTask()
        {
            /* Configuratie laden */
            Double.TryParse(System.Configuration.ConfigurationManager.AppSettings["wp7NotificationAskForLocationToastTimespan"].ToString(), out askForLocationToastTimespan);

            timer = new System.Timers.Timer(int.Parse(System.Configuration.ConfigurationManager.AppSettings["wp7NotificationTaskInterval"].ToString()));
            timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            timer.Enabled = true;

            LogHelper.LogMessage(String.Format("WP7NotificationTask(): task scheduled (interval = {0} minutes)", timer.Interval / 1000 / 60));
            OnTimedEvent(null, null);
        }

        private void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            LogHelper.LogMessage("WP7NotificationTask.OnTimedEvent()");

            //Stuur een request location update Toast naar alle WP7 gebruikers die binnen een vooraf gedefineerde tijd geen locatie update gestuurd hebben.
            using (ISession session = NHibernateHelper.GetSessionFactory().OpenSession())
            {
                IList<UserSession> userSessions = session.Query<UserSession>()
                                                         .Where<UserSession>(us => us.MobilePhoneType == Common.Classes.MobilePhoneTypeEnum.WindowsPhone7 && !us.LocationUpdateRequested && us.LastLocationUpdate != null && DateTime.UtcNow.AddMilliseconds(-askForLocationToastTimespan) >= us.LastLocationUpdate)
                                                         .ToList<UserSession>();
                foreach (UserSession us in userSessions)
                {
                    NotificationManager.Current.Notify(us.WP7PushNotifactionURL, NotificationFactory.PrepareToastLocationUpdate());
                    us.LocationUpdateRequested = true;
                    session.SaveOrUpdate(us);
                }
                using (ITransaction trans = session.BeginTransaction())
                {
                    trans.Commit();
                }
            }

            LogHelper.LogMessage("WP7NotificationTask.OnTimedEvent(): Done");
        }
    }
}
